<template>
  <div id="COORDINATE_MANAGEMENT_MAP" class="tdt_map" v-loading="isShowMapLoading"></div>
  <!-- 修改坐标弹窗 -->
  <a-modal
    v-model:visible="isShowEditCoordinateModal"
    title="修改设备坐标"
    @ok="editCoordinateDialogOkClick"
    @cancel="editCoordinateDialogCancelClick"
  >
    <div class="edit_coordinate_modal_box">
      <div class="item_box">
        <span class="label">经度</span>
        <a-input v-model:value="editDevInfo.lng" style="width: 200px" placeholder="请输入经度" />
      </div>
      <div class="item_box">
        <span class="label">纬度</span>
        <a-input v-model:value="editDevInfo.lat" style="width: 200px" placeholder="请输入纬度" />
      </div>

      <a-button
        class="select_coordinate_btn"
        style="width: 110px"
        type="primary"
        @click="selectDevCoordinateClick"
      >
        <img class="select_co_icon" src="./image/select_co_icon.svg" alt="" />
        <span>选取坐标</span>
      </a-button>
    </div>
  </a-modal>

  <a-alert
    v-if="isSelectCoordinate"
    message="当前是选取坐标模式，请在地图上双击某个位置获取坐标"
    class="select_coordinate_tip_alert"
    type="info"
    show-icon
  />

  <!-- 搜索设备 -->
  <a-card class="search_dev_card" v-if="isShowSearchDevCard">
    <a-form layout="inline">
      <a-form-item label="设备名称">
        <a-select
          allowClear
          v-model:value="devSearchName"
          show-search
          placeholder="请选择"
          style="width: 200px"
          :options="punctuationDataList"
          :fieldNames="{
            label: 'devName',
            value: 'devName'
          }"
          @change="punctuationSelectChange"
        >
        </a-select>
      </a-form-item>
    </a-form>
  </a-card>

  <!-- 搜索设备折叠按钮 -->
  <a-tooltip v-if="isShowSearchDevCard">
    <template #title>折叠搜索设备卡片</template>
    <a-button type="default" size="large" class="zd_search_btn" @click="zdSearchDevCardClick">
      <template #icon>
        <MenuFoldOutlined />
      </template>
    </a-button>
  </a-tooltip>

  <!-- 搜索设备展开按钮 -->
  <a-tooltip v-else>
    <template #title>展开搜索设备卡片</template>
    <a-button type="default" size="large" class="zk_search_btn" @click="zkSearchDevCardClick">
      <template #icon>
        <MenuUnfoldOutlined />
      </template>
    </a-button>
  </a-tooltip>

  <!-- notSetCoordinateDevList -->
  <a-card class="not_set_coord_dev_list_card" v-if="isShowNotSetCoordinateDevList">
    <div class="not_set_coord_dev_list_box">
      <div class="not_set_title_box">
        <span class="title_text">未设置坐标设备列表</span>
      </div>
      <div class="dev_list_box" v-if="notSetCoordinateDevList.length > 0">
        <div class="dev_item_box" v-for="(dev, indexD) in notSetCoordinateDevList" :key="indexD">
          <span class="dev_name">{{ dev.devName }}</span>
          <a-button size="small" type="primary" @click="setNotSetCoordinateDevClick(dev.devId)">
            <span style="font-size: 13px">设置坐标</span>
          </a-button>
        </div>
      </div>

      <div class="not_data_box" v-else>
        <span class="not_data_text">暂无数据</span>
      </div>
    </div>
  </a-card>

  <!-- 未设置坐标设备列表折叠按钮 -->
  <a-tooltip v-if="isShowNotSetCoordinateDevList">
    <template #title>折叠未设置坐标设备列表</template>
    <a-button
      type="default"
      size="default"
      class="zd_not_set_coord_btn"
      @click="zdNotSetCoordinateDevListClick"
    >
      <template #icon>
        <MenuFoldOutlined />
      </template>
    </a-button>
  </a-tooltip>

  <!-- 未设置坐标设备列表展开按钮 -->
  <a-tooltip v-else>
    <template #title>展开未设置坐标设备列表</template>
    <a-button
      type="default"
      size="large"
      class="zk_not_set_coord_btn"
      @click="zkNotSetCoordinateDevListClick"
    >
      <template #icon>
        <MenuUnfoldOutlined />
      </template>
    </a-button>
  </a-tooltip>
</template>

<script>
  import {defineComponent, nextTick, watch, h} from 'vue'
  import './index.scss'
  import './infoWin.scss'
  import loading from '@/components/loading/loading'
  export default defineComponent({
    name: 'TdtMap'
  })
</script>
<script setup>
  import cityGeo from './data/330000.json'
  import {getUserId} from '@/libs/auth'
  import {selectDevCoordinateApi, editDevCoordinateApi} from '@/api/coordinateManagement'
  import {createInfoWinContent} from './utils.js'
  import CloseImg from './image/close.svg'
  import _ from 'lodash'
  import {message} from 'ant-design-vue'
  import {
    SearchOutlined,
    DownloadOutlined,
    CaretLeftOutlined,
    LeftOutlined,
    MenuFoldOutlined,
    RightOutlined,
    MenuUnfoldOutlined
  } from '@ant-design/icons-vue'

  // 搜索设备名称
  const devSearchName = ref('')

  // 是否显示搜索设备卡片的标识
  const isShowSearchDevCard = ref(true)

  // 是否显示未设置坐标设备列表的标识
  const isShowNotSetCoordinateDevList = ref(true)

  // 搜索设备列表
  const punctuationDataList = ref([])

  // 未设置坐标设备列表
  const notSetCoordinateDevList = ref([])

  // 折叠未设置坐标设备列表按钮点击事件
  const zdNotSetCoordinateDevListClick = () => {
    isShowNotSetCoordinateDevList.value = false
  }

  // 展开未设置坐标设备列表按钮点击事件
  const zkNotSetCoordinateDevListClick = () => {
    isShowNotSetCoordinateDevList.value = true
  }

  // 折叠搜索设备卡片按钮点击事件
  const zdSearchDevCardClick = () => {
    isShowSearchDevCard.value = false
  }

  // 展开搜索设备卡片按钮点击事件
  const zkSearchDevCardClick = () => {
    isShowSearchDevCard.value = true
  }

  // 搜索设备change事件
  const punctuationSelectChange = e => {
    console.log('搜索设备', e)
    // 隐藏所有设备标注(marker)和信息窗口
    window.map.clearOverLays()
    window.map.closeInfoWindow()
    // 判断是选择还是清空
    if (e) {
      // 根据设备名称获取设备列表
      let showDevList = mapDevList.value.filter(item => {
        return item.devName == e
      })
      let cenerLngLat = new T.LngLat(showDevList[0].lng, showDevList[0].lat)

      // 设置地图中心点和地图缩放等级
      window.map.centerAndZoom(cenerLngLat, 11)
      createMapPunctuation(showDevList)
    } else {
      let cenerLngLat = new T.LngLat(centerLngLat.value[0], centerLngLat.value[1])
      // 设置地图中心点和地图缩放等级
      window.map.centerAndZoom(cenerLngLat, 11)
      createMapPunctuation(mapDevList.value)
    }
  }

  // 是否是选取坐标的标识
  const isSelectCoordinate = ref(false)

  // 是否显示修改坐标弹窗的标识
  const isShowEditCoordinateModal = ref(false)

  // 当前修改坐标的设备信息
  const editDevInfo = ref({})

  // 设置未设置坐标设备点击事件
  const setNotSetCoordinateDevClick = devId => {
    editDevCoordinateClick(devId)
    selectDevCoordinateClick()
  }

  // 修改坐标点击事件
  const editDevCoordinateClick = devId => {
    let dev = mapDevList.value.find(item => item.devId == devId)
    console.log('修改坐标', dev)
    editDevInfo.value = _.cloneDeep(dev)

    console.log(editDevInfo.value)

    // 打开修改坐标弹窗
    isShowEditCoordinateModal.value = true
  }

  // 修改坐标弹窗确定点击事件
  const editCoordinateDialogOkClick = async () => {
    let data = {
      devBaseDataId: editDevInfo.value.devBaseData.devBaseDataId,
      longitude: editDevInfo.value.lng,
      latitude: editDevInfo.value.lat
    }
    await editDevCoordinateApi(data)
      .then(res => {
        if (res.result == 'success') {
          // message.success('修改设备坐标成功!')

          isShowEditCoordinateModal.value = false
        } else {
          message.error(res.msg)
        }
      })
      .catch(() => {
        message.error('修改设备坐标失败,请联系管理员')
      })
      .finally(() => {
        selectDevCoordinateFunc()
      })
  }

  // 修改坐标弹窗取消点击事件
  const editCoordinateDialogCancelClick = () => {
    isSelectCoordinate.value = false
    // 关闭弹窗时，清空修改坐标信息
    editDevInfo.value = {}
    // createInfoWinContent()
    createMapPunctuation(mapDevList.value)
  }

  // 选取坐标按钮点击事件
  const selectDevCoordinateClick = () => {
    isSelectCoordinate.value = true
    isShowEditCoordinateModal.value = false

    console.log('#禁用双击放大')

    window.map.disableDoubleClickZoom() // 禁用双击放大

    console.log('选取坐标')
  }

  // 取消选取坐标
  const cancelSelectCoordinate = () => {
    isSelectCoordinate.value = false
  }

  // 监听是否是选取坐标的标识
  watch(isSelectCoordinate, (newV, oldV) => {
    console.log('newV', newV)

    if (newV) {
      // 隐藏所有设备标注(marker)和信息窗口
      window.map.clearOverLays()
      window.map.closeInfoWindow()
    } else {
    }
  })

  // map对象
  window.map = null

  // 地图中心点坐标
  const centerLngLat = ref([120.26548, 30.33295])

  // 初始化地图函数
  const initMap = () => {
    window.map = new T.Map('COORDINATE_MANAGEMENT_MAP')

    // 创建地图中心点实例
    // let cenerLngLat = new T.LngLat(120.21781, 30.255328)
    let cenerLngLat = new T.LngLat(centerLngLat.value[0], centerLngLat.value[1])
    // 设置地图中心点和地图缩放等级
    window.map.centerAndZoom(cenerLngLat, 11)
    console.log(map)
    window.map.setMapType(TMAP_NORMAL_MAP)

    var lc = new T.LocalCity()
    lc.location(function (e) {
      // alert(e.cityName)
      // var marker = new T.Marker(e.lnglat)
      // map.addOverLay(marker)
      console.log('1111')
    })

    // 添加区域边框
    initBorder()

    // 添加控件
    initControl()

    // 是否触发map双击的标识
    let isMapProcessing = false

    // 添加双击事件
    window.map.addEventListener('dblclick', e => {
      if (isMapProcessing) return
      isMapProcessing = true

      console.log(isSelectCoordinate.value)

      if (!isSelectCoordinate.value) return

      console.log('双击地图', e)

      // 判断选取的坐标是否为空
      let sLngLat = e.lnglat
      editDevInfo.value.lng = sLngLat.lng
      editDevInfo.value.lat = sLngLat.lat

      isShowEditCoordinateModal.value = true

      cancelSelectCoordinate()

      createMapPunctuation(mapDevList.value)

      setTimeout(() => {
        isMapProcessing = false
        // 开启地图双击放大
        window.map.enableDoubleClickZoom()
      }, 100)
    })
  }

  // 初始化控件
  const initControl = () => {
    // 缩放控件
    let scaleControl = new T.Control.Zoom()
    scaleControl.setPosition(T_ANCHOR_TOP_RIGHT)

    // 鹰眼控件
    let miniMap = new T.Control.OverviewMap({
      isOpen: true,
      size: new T.Point(150, 150)
    })
    // 向地图上添加控件
    window.map.addControl(scaleControl)
    window.map.addControl(miniMap)

    createMapPunctuation(mapDevList.value)
  }

  // 初始化区域边框
  const initBorder = () => {
    var bdary = cityGeo.features[0].geometry.coordinates[0][0]
    var pointArrays = new Array()
    for (var i = 0; i < bdary.length; i++) {
      var xyArr = bdary[i][0]
      var ptAr = bdary[i][1]
      pointArrays.push(new T.LngLat(xyArr, ptAr))
    }
    var border = new T.Polygon(pointArrays, {
      color: '#9cdcda',
      weight: 3,
      opacity: 1,
      fillOpacity: 0
    })
    //向地图上添加线
    window.map.addOverLay(border)
  }

  // 设备列表信息
  const mapDevList = ref([])

  // 生成点位
  const createMapPunctuation = list => {
    list.forEach(dev => {
      console.log('设备信息', dev)

      // 判断坐标信息是否完整
      if (dev.lng == '' || dev.lat == '') return

      // 创建marker
      let marker1 = new T.Marker(new T.LngLat(dev.lng, dev.lat), {
        icon: new T.Icon({
          iconUrl: `https://d.lohand.com:1112/images/ConstantBlueCloud/WEB/${
            dev.devStatus == '在线' ? 'on_line_map_dev1' : 'off_line_map_dev2'
          }.png`,
          iconSize: new T.Point(40, 40),
          draggable: true,
          iconAnchor: new T.Point(20, 20)
        })
      })

      // 信息窗口
      let markerInfoWin = new T.InfoWindow()
      let infoContent = createInfoWinContent(dev, editDevCoordinateClick)
      markerInfoWin.setContent(infoContent)

      // 移除可能存在的旧监听器
      marker1.removeEventListener('click')
      marker1.removeEventListener('dblclick')

      let clickTimer = null
      let isDoubleClick = false

      // 添加单击事件监听
      marker1.addEventListener('click', e => {
        // 如果是双击触发的单击事件，则忽略
        if (isDoubleClick) {
          isDoubleClick = false
          return
        }

        // 设置计时器延迟执行单击事件
        clickTimer = setTimeout(() => {
          // 这里添加你的marker单击处理逻辑
          console.log('Marker被单击了', e)

          // 打开信息窗口
          marker1.openInfoWindow(markerInfoWin)

          let editZBEl = document.querySelector('.edit_zb_btn')
          editZBEl.onclick = () => {
            editDevCoordinateClick(editZBEl.getAttribute('data-devId'))
          }
        }, 200) // 200ms延迟足够区分单击和双击
      })

      // 是否触发双击的标识
      let isProcessing = false

      // 添加双击事件监听
      marker1.addEventListener('dblclick', function (e) {
        if (isProcessing) return
        isProcessing = true

        // 清除单击事件的计时器
        clearTimeout(clickTimer)
        isDoubleClick = true

        // 阻止事件冒泡
        if (e && e.stopPropagation) {
          e.stopPropagation()
        } else {
          window.event.cancelBubble = true // IE兼容处理
        }

        // 这里添加你的marker双击处理逻辑
        console.log('Marker被双击了', e)

        setTimeout(() => {
          isProcessing = false
        }, 100)
      })

      marker1.data = {
        a: 1,
        b: 2
      }

      // 添加marker
      window.map.addOverLay(marker1)
    })
  }

  // 查询点位信息
  const selectDevCoordinateFunc = async () => {
    window.map.clearOverLays()
    window.map.closeInfoWindow()
    isShowMapLoading.value = true
    let params = {
      userId: getUserId()
    }
    await selectDevCoordinateApi(params)
      .then(res => {
        console.log(res)

        // 搜索坐标设备列表
        let searchDevList = []

        // 未设置坐标设备列表
        let newNotSetCoordinateDevList = []

        let newDevList = res.data.map((dev, index) => {
          if (isInitMap.value) {
            if (index == 0) {
              centerLngLat.value = [dev.devBaseData.longitude, dev.devBaseData.latitude]
              // window.map.set
              let cenerLngLat = new T.LngLat(centerLngLat.value[0], centerLngLat.value[1])
              // 设置地图中心点和地图缩放等级
              window.map.centerAndZoom(cenerLngLat, 11)
            }
            isInitMap.value = false
          }

          // 判断坐标信息是否完整
          if (
            dev.devBaseData.longitude != '' &&
            dev.devBaseData.latitude != '' &&
            dev.devBaseData.longitude != null &&
            dev.devBaseData.latitude != null &&
            dev.devBaseData.longitude != undefined &&
            dev.devBaseData.latitude != undefined
          ) {
            searchDevList.push(dev)
          } else {
            newNotSetCoordinateDevList.push(dev)
          }

          return {
            devId: dev.devBaseData.devId,
            devName: dev.devName,
            lat: dev.devBaseData.latitude,
            lng: dev.devBaseData.longitude,
            devGId: dev.devGId,
            devStatus: dev.devStatus,
            checkDataRsp: dev.checkDataRsp,
            devBaseData: dev.devBaseData
          }
        })
        mapDevList.value = newDevList
        punctuationDataList.value = searchDevList.map(dev => {
          return {
            devId: dev.devBaseData.devId,
            devName: dev.devName,
            lat: dev.devBaseData.latitude,
            lng: dev.devBaseData.longitude,
            devGId: dev.devGId,
            devStatus: dev.devStatus,
            checkDataRsp: dev.checkDataRsp,
            devBaseData: dev.devBaseData
          }
        })

        notSetCoordinateDevList.value = newNotSetCoordinateDevList.map(dev => {
          return {
            devId: dev.devBaseData.devId,
            devName: dev.devName,
            lat: dev.devBaseData.latitude,
            lng: dev.devBaseData.longitude,
            devGId: dev.devGId,
            devStatus: dev.devStatus,
            checkDataRsp: dev.checkDataRsp,
            devBaseData: dev.devBaseData
          }
        })

        console.log('设备列表', mapDevList.value)
        console.log('未设置坐标设备列表', notSetCoordinateDevList.value)

        // initMap()

        createMapPunctuation(mapDevList.value)
      })
      .finally(() => {
        isShowMapLoading.value = false
      })
  }

  // 是否初始化地图
  const isInitMap = ref(true)

  // 是否显示地图加载动画标识
  const isShowMapLoading = ref(false)

  // nextTick
  nextTick(() => {})

  // init
  onMounted(() => {
    initMap()
    selectDevCoordinateFunc()
  })
</script>

<style lang="scss" scoped></style>
